package at.fhj.mobsecdev.cookit.adapter;

import java.util.List;
import android.annotation.SuppressLint;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import at.fhj.mobsecdev.cookit.R;
import at.fhj.mobsecdev.cookit.model.Recipe;
import at.fhj.mobsecdev.cookit.util.lazylist.ImageLoader;
import at.fhj.mobsecdev.cookit.webrequests.WebServiceUrls;

/** 
 * Adapter of recipe list in MainActivity
 */
public class RecipeAdapter extends ArrayAdapter<Recipe> {

    private final Context context;
    private final List<Recipe> values;
    private ImageLoader imageLoader;
	  
	  
	public RecipeAdapter(Context context, int resource, List<Recipe> objects) {
		super(context, resource, objects);
		
		this.context = context;
		this.values = objects;
		
		imageLoader = new ImageLoader(context);
	}
	
	@SuppressLint("ViewHolder")
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		
		View recipeListElementView = inflater.inflate(R.layout.recipe_list_element, parent, false);
		
		TextView nameView = (TextView)recipeListElementView.findViewById(R.id.name);
		TextView ownerView = (TextView)recipeListElementView.findViewById(R.id.owner);
		TextView difficultyView = (TextView)recipeListElementView.findViewById(R.id.difficulty);
		ImageView thumbImageView = (ImageView)recipeListElementView.findViewById(R.id.thumbImage);
		
		/* If recipe is vegetarian, indicate in name */
		String name = values.get(position).getName();
		if(values.get(position).isVegetarian())
		{
			name += " " + parent.getResources().getString(R.string.vegetarian_indicator);
		}
		
		nameView.setText(name);
		ownerView.setText(values.get(position).getOwnerUsername());
		difficultyView.setText(values.get(position).getDifficulty());
		
		/* Load & cache thumbnail for recipe */
		imageLoader.DisplayImage(WebServiceUrls.IMAGE_URL + WebServiceUrls.THUMBNAIL_PREFIX + values.get(position).getImageFilePath(), thumbImageView);

		return recipeListElementView;
	}
	
	/**
	 * Appends lis tof recipes to adapter
	 * @param newRecipes list of recipes to add
	 */
	public void addRecipes(List<Recipe> newRecipes)
	{
		for(Recipe recipe : newRecipes)
		{
			values.add(recipe);
		}
	}
	
	/**
	 * Clears all recipes from adapter
	 */
	public void clear()
	{
		values.clear();
		this.notifyDataSetChanged();
	}
}
